package test.luin.pers.myapplication;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinggrid.iappoffice.IAppOffice;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import test.luin.pers.myapplication.common.DialogMsg;

import static android.content.ContentValues.TAG;

public class Basic extends CheckPermissionsActivity implements View.OnClickListener, constant {

    final static String COPY_RIGHT = "SxD/phFsuhBWZSmMVtSjKZmm/c/3zSMrkV2Bbj5tznSkEVZmTwJv0wwMmH/+p6wLiUHbjadYueX9v51H9GgnjUhmNW1xPkB++KQqSv/VKLDsR8V6RvNmv0xyTLOrQoGzAT81iKFYb1SZ/Zera1cjGwQSq79AcI/N/6DgBIfpnlwiEiP2am/4w4+38lfUELaNFry8HbpbpTqV4sqXN1WpeJ7CHHwcDBnMVj8djMthFaapMFm/i6swvGEQ2JoygFU38558QhLaX/Jr1koWwK15kEmTvMG/nhvTilibTVNrCtS1VzVwUlmsSQF90/OYTdIhuI7ZTJqU764j1aPQnpiJKCoW/T3lHnHSqUG9ekm19Ty6lZhbc0wZsYY7F8fGE4DHZs4YOxNd7fnxKM4Dd4Klf1+OBmeDcECRDSxKMJbBZX2hOjA9xBaBPEEybxot0XBztGIYfNWOY83ltjqKjeToDSIzRqZYYUbAtzuYjy8C+3Ix04ev8Hm/as8N+FyWSdRWDRk0QFLuqgyKytzjbVWa9W3+KjjXk4eWYscdbEPDzss=";
    //    final static String URL_Path =  "http://192.168.2.124:8081/test.docx";
    // final static String URL_Path = "http://192.168.2.124:8081/SkylandAttach.data?action=DownAttach&OLDNAME=%E9%99%84%E4%BB%B62%EF%BC%9A%E5%8D%97%E5%AE%81%E5%B8%82%E5%86%9C%E4%B8%9A%E5%A7%94%E5%85%B3%E4%BA%8E%E8%87%AA%E6%B2%BB%E5%8C%BA%E5%86%9C%E4%B8%9A%E5%86%9C%E6%9D%91%E6%B1%A1%E6%9F%93%E6%B2%BB%E7%90%86%E6%94%BB%E5%9D%9A%E5%AE%9E%E6%96%BD%E6%96%B9%E6%A1%88%EF%BC%88%E7%AC%AC%E4%BA%8C%E6%AC%A1%EF%BC%89%E5%BE%81%E6%B1%82%E6%84%8F%E8%A7%81%E7%A8%BF%E7%9A%84%E5%8F%8D%E9%A6%88%E6%84%8F%E8%A7%8120190202.pdf&PATH=%E9%99%84%E4%BB%B62%EF%BC%9A-undefined-0141852038862.pdf&folder=C1092137368101&FileType=wfAttachFile";
    final static String URL_Path = "http://192.168.2.174:5566/iWebOfficeService.data?action=ProcessRequest";
    //服务器存储路径
    public static String FILEPATH = "D:\\test2.doc";

    private Button btn_openDoc;

    private Button btn_openWebDoc;

    private Button btn_testProgressBar;

    private Button btn_tip;

    private String fileName;//文件绝对路径

    public IAppOffice iappoffice;//控件对象

    private NumberProgressBar bnp;

    private static BasicReceive getRec;

    private static final String SDCARD_ROOT_PATH = Environment
            .getExternalStorageDirectory().getPath().toString();//SD

    final static String Des_Path = SDCARD_ROOT_PATH + "/ZHT/doc/test2.doc";

    private Context mContext = Basic.this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic);
        //绑定按钮事件
        initBtn();
        //设置需要打开的目标文件;
        fileName = SDCARD_ROOT_PATH + "/test1.docx";
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }

        //拷贝文件到指定路径下;
        try {
            copyAssetsFileToSDCard("fwg.docx", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //初始化iAppOffice, 注：先设置授权码，后调用init();
        iappoffice = new IAppOffice(this);
        iappoffice.setFileProviderAuthor("test.luin.pers.myapplication.fileProvider");
        iappoffice.setCopyRight(COPY_RIGHT);
        int isSuccess = iappoffice.init();
        //初始化文件夹
        initDoccument();
        registerIntentFilters();
    }

    public void initDoccument() {
        judeDirExists(new File(SDCARD_ROOT_PATH + "/ZHT/doc/"));
    }

    public void initBtn() {
        btn_openDoc = (Button) findViewById(R.id.btn_openDoc);
        btn_openDoc.setOnClickListener(this);
        btn_openWebDoc = (Button) findViewById(R.id.btn_openWebDoc);
        btn_openWebDoc.setOnClickListener(this);
        btn_tip = (Button) findViewById(R.id.btn_tip);
        btn_tip.setOnClickListener(this);
        btn_testProgressBar = (Button) findViewById(R.id.btn_testProgressBar);
        btn_testProgressBar.setOnClickListener(this);
        bnp = (NumberProgressBar) findViewById(R.id.progressBarNormal);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_openDoc:
                openDocument();
                break;
            case R.id.btn_openWebDoc:
                openWebDocument();
                break;
            case R.id.btn_testProgressBar:
                progressBarTest();
                break;
            case  R.id.btn_tip:
                click01(v);
                break;
        }
    }

    /**
     * 弹出确定取消对话框
     *
     * @param view
     */
    public void click01(View view) {
        DialogMsg dialogMsg = new DialogMsg(Basic.this);
        dialogMsg.showDialog();
    }

    public void progressBarTest() {
        bnp.setProgress(90);
    }

    //    打开网络文件
    public void openWebDocument() {
        if (iappoffice.isWPSInstalled()) {//判断是否安装WPS
            new Thread() {
                public void run() {
                    downloadFile3();
                    String filePath = Des_Path;
                    iappoffice.setUserName("云景小陆");
                    iappoffice.setFileName(filePath);
                    iappoffice.setIsReviseMode(true);
                    iappoffice.setEditMode(true);
                    iappoffice.setShowReviewingPaneRightDefault(false);
                    iappoffice.appOpen(true);//打开文档，这里true表示打开本地文档
                }
            }.start();
        } else {
            Toast.makeText(this, "请安装WPS专业版！", Toast.LENGTH_SHORT).show();
        }
    }

    public void updateProgress(double total, double loaded) {
        double a = loaded / total;
        double persent = a * 100;
        int result = Double.valueOf(persent).intValue();//转换为Int类型
        bnp.setProgress(result);
    }

    static void downloadFile3() {
        try {
            HttpURLConnection conn;
            int bytesum = 0;
            int byteread = 0;
            Gson gson = new Gson();
//            String URL_Path ="http://192.168.2.174:5566/iWebOfficeService.data?action=ProcessRequest";
            Map<String, String> map = new HashMap<String, String>();
            map.put("FILEPATH", FILEPATH);
            map.put("OPTION", "LOADFILE");
            String formData = URLEncoder.encode(gson.toJson(map), "utf-8");
            String p = URL_Path + "&FormData=" + formData;
            URL url = new URL(p);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);// 超时5秒
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                FileOutputStream fs = new FileOutputStream(Des_Path);
                int fileSize = conn.getContentLength();// 根据响应获取文件大小
                byte[] buffer = new byte[1204];
                int length;
                while (((byteread = is.read(buffer)) != -1)) {
                    bytesum += byteread;
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void donwLoadFile() {
        try {
            HttpURLConnection conn;
            int bytesum = 0;
            int byteread = 0;
            Gson gson = new Gson();
            Map<String, String> map = new HashMap<String, String>();
            map.put("FILEPATH", "D:\\软件项目\\跟新\\南宁市环境保护局关于报送广西壮族自治区农业农村污染治理攻坚战实施方案（第二次征求意见稿）修改意见的请示.doc");
            map.put("OPTION", "LOADFILE");
            String formData = URLEncoder.encode(gson.toJson(map), "utf-8");
            String param_path = URL_Path + "&FormData=" + formData;
            URL url = new URL(param_path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);// 超时5秒
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                FileOutputStream fs = new FileOutputStream(Des_Path);
                int fileSize = conn.getContentLength();// 根据响应获取文件大小
                byte[] buffer = new byte[1204];
                int length;
                while (((byteread = is.read(buffer)) != -1)) {
                    bytesum += byteread;
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void openDocument() {
        if (iappoffice.isWPSInstalled()) {//判断是否安装WPS
            iappoffice.setFileName(fileName);//设置文件名
            iappoffice.setIsReviseMode(false);//设置是否显示痕迹
            iappoffice.appOpen(true);//打开文档，这里true表示打开本地文档
        } else {
            Toast.makeText(this, "请安装WPS专业版！", Toast.LENGTH_SHORT).show();
        }
    }

    //考本文件到SD卡根目录
    private void copyAssetsFileToSDCard(String fileName, String toFilePath)
            throws IOException {
        File file = new File(toFilePath);
        if (file.exists()) {
            return;
        }
        InputStream myInput;
        OutputStream myOutput = new FileOutputStream(toFilePath);
        myInput = getAssets().open(fileName);
        byte[] buffer = new byte[1024];
        int length = myInput.read(buffer);
        while (length > 0) {
            myOutput.write(buffer, 0, length);
            length = myInput.read(buffer);
        }
        myOutput.flush();
        myInput.close();
        myOutput.close();
    }

    // 判断文件夹是否存在
    public static void judeDirExists(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                System.out.println("dir exists");
            } else {
                System.out.println("the same name file exists, can not create dir");
            }
        } else {
            System.out.println("dir not exists, create it ...");
            file.mkdir();
        }
    }

    public void registerIntentFilters() {
        if (getRec == null) {
            IntentFilter backFilter = new IntentFilter();
            backFilter.addAction(BROADCAST_BACK_DOWN);
            IntentFilter homeFilter = new IntentFilter();
            homeFilter.addAction(BROADCAST_HOME_DOWN);
            IntentFilter saveFilter = new IntentFilter();
            saveFilter.addAction(BROADCAST_FILE_SAVE);
            IntentFilter closeFilter = new IntentFilter();
            closeFilter.addAction(BROADCAST_FILE_CLOSE);
            IntentFilter notFindFilter = new IntentFilter();
            notFindFilter.addAction("com.kinggrid.notfind.office");
            IntentFilter savePicFilter = new IntentFilter();
            savePicFilter.addAction(BROADCAST_FILE_SAVE_PIC);
            IntentFilter showHandwriteFilter = new IntentFilter();
            showHandwriteFilter.addAction("com.kinggrid.iappoffice.showHandwrite");
            IntentFilter homekeyFilter = new IntentFilter();
            homekeyFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            IntentFilter saveAsPDFFilter = new IntentFilter();
            saveAsPDFFilter.addAction(BROADCAST_FILE_SAVEAS_PDF);
            IntentFilter openEndFilter = new IntentFilter();
            openEndFilter.addAction(BROADCAST_FILE_OPEN_END);

            getRec = new BasicReceive();
            registerReceiver(getRec, backFilter);
            registerReceiver(getRec, homeFilter);
            registerReceiver(getRec, saveFilter);
            registerReceiver(getRec, closeFilter);
            registerReceiver(getRec, notFindFilter);
            registerReceiver(getRec, savePicFilter);
            registerReceiver(getRec, showHandwriteFilter);
            registerReceiver(getRec, homekeyFilter);
            registerReceiver(getRec, saveAsPDFFilter);
            registerReceiver(getRec, openEndFilter);
        }
    }


    protected void onDestroy() {
        if (iappoffice != null) {
            iappoffice.unInit();
        }
        super.onDestroy();
    }
}
